package com.lambkit.plugin.undertow;

import com.lambkit.core.Lambkit;
import com.lambkit.core.LambkitContext;
import com.lambkit.core.task.http.HttpWorkCenter;
import com.lambkit.servlet.LambkitServletContext;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yangyong(孤竹行)
 */
public class ServletFilter implements Filter {
    private String appName = LambkitContext.MAIN_APP;
    private HttpWorkCenter workCenter;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        appName = filterConfig.getInitParameter("appName");
        System.out.println(getClass() + " init appName: " + appName);
        workCenter = Lambkit.app(appName).context().getWorkCenter(HttpWorkCenter.class);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)request;
        HttpServletResponse httpServletResponse = (HttpServletResponse)response;
        String target = httpServletRequest.getRequestURI();
        //System.out.println(getClass() + " request uri: " + target);
        if(target.indexOf(".") > 0) {
            return;
        }
        workCenter.handle(new LambkitServletContext(httpServletRequest, httpServletResponse));
    }
}
